const co = require('co')
const {
	select,
	insert,
	update,
	selectOne,
} = require('../db-mysql')

const table = 'tb_user'
const fields = [
	'id',
	'account',
	'password',
	'nickname',
	'email',
	'create_date',
	'modify_date',
	'is_locked_out',
	'last_login_date',
	'realname',
	'image_url',
	'user_role'
]

module.exports = {
	addUser(params) {
		let values = []
		let addFields = fields.filter((val, idx) => {
			if (val == 'id' || val == 'is_locked_out' || val == 'user_role')
				return false
			else if (val == 'create_date' || val == 'modify_date' || val == 'last_login_date')
				values.push("NOW()")
			else if (val == 'password')
				values.push(`PASSWORD(${params[val]})`)
			else
				values.push(`'${params[val] || ''}'`)
			return true
		});
		return insert({
			table,
			fields: addFields,
			values,
		});
	},

	updateUser() {

	},

	queryUser(params) {
		let where = []
		let paramArr = Object.keys(params)
		for (let i = 0; i < paramArr.length; i++) {
			let key = paramArr[i]
			let val = `'${params[key]}'`
			if (key == 'password')
				val = `PASSWORD(${val})`
			where.push(`${key} = ${val}`)
		}
		return select({
			table,
			fields,
			where,
		})
	},

	listUser() {
		return select({
			table,
			fields,
		})
	},

	updatePassword(params) {
		let {
			id,
			account,
			password,
			newpassword,
			type,
			nickname,
			email,
		} = params
		let updates = []
		let where = [`id = '${id}'`, `account = '${account}'`]
		if (type == 'pwd')
			updates.push(`password = PASSWORD(${newpassword})`)
		else if (type == 'email')
			updates.push(`email = '${email}'`)
		else if (type == 'nickname')
			updates.push(`nickname = '${nickname}'`)
		return co(function*() {
			let result = yield update({
				table,
				updates,
				where: where.concat(`password = PASSWORD(${password})`),
			})
			if (result.affectedRows < 1)
				return {
					error: '修改失败！',
					info: result,
				}
			return selectOne({
				table,
				fields,
				where,
			})
		});
	}
}